#include "SDLSelectableRegion.h"

using namespace sdl;

SDLSelectableRegion::SDLSelectableRegion(int xpos, int ypos, int w, int h, SDLSurface* surface) : x(xpos), y(ypos), width(w), height(h), sdlSurface(surface)
{
	label = "";
	borderColor = 0;
	backgroundColor = 0;
	font = 0;
	initialize();
}

SDLSelectableRegion::~SDLSelectableRegion(void)
{
	delete borderColor;
	delete backgroundColor;
}

void SDLSelectableRegion::draw(void)
{
	drawBorder();
	drawBackground();
	drawContents();
}

void SDLSelectableRegion::drawBorder(void)
{
	boxRGBA(sdlSurface->getSurface(), x, y, x+width, y+height, borderColor->getRed(), borderColor->getGreen(),
		borderColor->getBlue(), borderColor->getAlpha());
}

void SDLSelectableRegion::drawBackground(void)
{
	boxRGBA(sdlSurface->getSurface(), x+1, y+1, x+width-1, y+height-1, 0, 0, 0, 255);
	boxRGBA(sdlSurface->getSurface(), x+2, y+2, x+width-2, y+height-2, backgroundColor->getRed(),
		backgroundColor->getGreen(), backgroundColor->getBlue(), backgroundColor->getAlpha());
}

void SDLSelectableRegion::drawContents(void)
{
	if (!font)
	{
		string message("No es posible abrir el font arial.ttf. El error reportado por SDL es: '");
		message.append(SDL_GetError()).append("'.");
		Logger::instance().log(message);
	}
	else
	{
		TTF_SetFontStyle(font, 0);
		SDL_Color color = {0, 0, 0};
		SDL_Surface* textSurface = TTF_RenderUTF8_Blended(font, label.c_str(), color) ;
		if (textSurface != NULL)
		{
			SDL_Rect source;
			source.x = 0;
			source.y = 0;
			source.w = width;
			source.h = height;

			SDL_Rect destination;
			destination.x = (width-textSurface->w)/2+x; //centra en x;
			destination.y = (height-textSurface->h)/2+y; //centra en y;
			destination.w = width;
			destination.h = height;
			SDL_BlitSurface(textSurface, &source, sdlSurface->getSurface(), &destination);
			SDL_FreeSurface(textSurface);
		}
	}
}

void SDLSelectableRegion::initialize(void)
{
	font = TTF_OpenFont("..\\fonts\\arial.ttf", 10);
	if (!font)
	{
		string message("No es posible abrir el font arial.ttf. El error reportado por SDL es: '");
		message.append(TTF_GetError()).append("'.");
		Logger::instance().log(message);
	}
	else if (height <= 0)
	{
		height = TTF_FontHeight(font);
	}
}
